<template>
  <div>
    <div v-show="flag" class="empty">
      <img src="../assets/img/car.jpg" />
      <p>购物车空空如也</p>
      <van-button type="info" size="mini" @click="shopping">去逛逛</van-button>
    </div>
    <div>
      <van-card
        v-for="(item ,i) in car"
        :key="item.id"
        :num="item.count"
        :price="item.price"
        :title="goodsLIst ? goodsLIst[i].title : ''"
        :thumb="goodsLIst ? goodsLIst[i].thumb_path : ''"
      >
        <div slot="footer">
          <van-stepper v-model="item.count" @change="num(item.id)" @plus="add1" @minus="sub1" />
        </div>
      </van-card>
    </div>
    <van-submit-bar :price="sum" button-text="提交订单" />
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      flag: false,
      car: [],
      id: '',
      sum: 0,
      goodsLIst: ''
    }
  },
  created() {
    this.getShopping()
  },
  methods: {
    ...mapMutations(['sub', 'add']),
    shopping() {
      this.$router.push('/goods/list')
    },
    async getShopping() {
      const shop = JSON.parse(window.localStorage.getItem('car'))
      if (shop === null) {
        this.flag = true
      } else {
        this.flag = false
        this.car = shop
        for (var i = 0; i < this.car.length; i++) {
          this.id += this.car[i].id + ','
        }
        this.id = this.id.substr(0, this.id.length - 1)
        this.totalPrice()
        // console.log(this.sum)
        const { data: res } = await this.$http.get(
          `/api/goods/getshopcarlist/${this.id}`
        )
        if (res.status !== 0) {
          return this.$toast.fail('获取商品数据失败！')
        }
        this.goodsLIst = res.message
      }
    },
    num(id) {
      localStorage.setItem('car', JSON.stringify(this.car))
      this.sum = 0
      this.totalPrice()
    },
    totalPrice() {
      for (var i = 0; i < this.car.length; i++) {
        this.sum += this.car[i].count * this.car[i].price
      }
      this.sum *= 100
    },
    add1() {
      this.add()
    },
    sub1() {
      this.sub()
    }
  },
  computed: {
    ...mapState(['count'])
  }
}
</script>

<style lang="less" scoped>
.empty {
  color: #ccc;
  padding: 15px 0;
  text-align: center;
  img {
    width: 100px;
  }
}
.van-card {
  margin: 10px 0;
}
</style>
